# encoding: utf-8
from flask_restplus import Resource
from app.extensions.api import Namespace
from app.modules.common.utils import DbCommit, checkToken
from . import parameters, schemas
from .models import EntranceInfo
from app.modules.zones.common import getZoneCodesByCodeS
from app.modules.apps.models import AppInfo

api = Namespace('entrance', description = "入口")  # pylint: disable=invalid-name


@api.route('/')
class GetEntranceList(Resource):
    @api.parameters(parameters.EntranceListParameters())
    @api.response(schemas.EntranceListSchema(many = False))
    @checkToken
    def get(self, args, **kwargs):
        """
        获取入口列表
        :param args:
        :return:
        """
        _env_name = args['env_name']
        _types = args['types']
        _zone_codes = args['zone_codes']
        _hasApp = args['hasApp']
        _current_status = args['current_status']

        _query = EntranceInfo.query.filter_by(env_name = _env_name)

        if _types is not None:
            _query = _query.filter(EntranceInfo.type.in_(str(_types).split(',')))
        if _zone_codes is not None:
            _query = _query.filter(EntranceInfo.zone_code.in_(getZoneCodesByCodeS(_env_name, zone_codes = _zone_codes)))
        if _current_status is not None:
            _query = _query.filter(EntranceInfo.current_status.in_(str(_current_status).split(',')))

        _list = _query.order_by(EntranceInfo.type.asc()).all()
        if _hasApp:
            for _e in _list:
                _e.apps = AppInfo.query.filter_by(entrance_id = _e.id, is_resource = '0').order_by(
                    AppInfo.app_name.asc(), AppInfo.group.asc()).all()

        return {'success': True, 'msg': '', 'data': _list}
